package com.mobile.collect.activitys;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.mobile.collect.AddPointEvent;
import com.mobile.collect.R;
import com.mobile.collect.beans.DeviceInfo;
import com.mobile.collect.beans.DevicePicInfo;
import com.mobile.collect.beans.DevicePointInfo;
import com.mobile.collect.db.EntityManager;
import com.mobile.collect.dialogs.BottomListDialog;
import com.mobile.collect.dialogs.SubmitTipDialog;
import com.mobile.collect.present.BasePresent;
import com.mobile.collect.utils.AppContents;
import com.mobile.collect.view.CopyDialog;
import com.mobile.collect.view.InputDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;
import cn.droidlover.xdroidmvp.base.BaseListActivity;
import cn.droidlover.xdroidmvp.base.BaseRecyclerAdapter;
import cn.droidlover.xdroidmvp.base.RecyclerViewHolder;
import cn.droidlover.xdroidmvp.cache.SharedPref;
import cn.droidlover.xdroidmvp.event.BusProvider;
import cn.droidlover.xdroidmvp.kit.Kits;
import cn.droidlover.xdroidmvp.kit.NLog;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;


public class DeviceUnitListActivity extends BaseListActivity<DevicePicInfo, BasePresent> {
    String deviceName;
    Long deviceDbId;

    @BindView(R.id.box_empty_tags)
    LinearLayout boxEmptyTags;
    @BindView(R.id.bottonLayout)
    LinearLayout bottonLayout;
    @BindView(R.id.inputEt)
    EditText inputEt;
    @BindView(R.id.copyBtn)
    Button copyBtn;
    @BindView(R.id.clearIv)
    ImageView clearIv;

    boolean isCopyModel;

    private List<DevicePicInfo> selectList = new ArrayList<>();

    private Map<String, List<String>> labelMap = new HashMap<>();

    @Override
    public int getContentViewId() {
        return R.layout.activity_unitlist;
    }

    @Override
    public void initView() {
        super.initView();
//        mItemTouchHelper.attachToRecyclerView(mRecyclerview);
//        mRefreshLayout.setEnableLoadmore(false);
//        mRefreshLayout.setEnableRefresh(false);
//        mRefreshLayout.setAutoLoadMore(false);
        titleTv.setText(deviceName);
        mainView = mRecyclerview;
        nodataView = boxEmptyTags;
        inputEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = inputEt.getText().toString();
                if (TextUtils.isEmpty(text)) {
                    clearIv.setVisibility(View.GONE);
                } else {
                    clearIv.setVisibility(View.VISIBLE);
                }
                getDataFromServer();
            }
        });
        clearIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inputEt.setText("");
            }
        });

//        mBaseAdapter.setLongClickListener(new ListItemLongClickListener() {
//            @Override
//            public void itemLongClick(int position) {
//                showBottomDialog(mBaseAdapter.getItemByPosition(position));
//            }
//        });
        if (AppContents.ISTEST || SharedPref.getInstance(this).getBoolean("quanxian", false)) {
            copyBtn.setVisibility(View.VISIBLE);
        } else {
            copyBtn.setVisibility(View.GONE);
        }
    }

    DeviceInfo mDeviceInfo;

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mDeviceInfo = EntityManager.getInstance().queryDeviceInfoById(deviceDbId);
        BusProvider.getBus().toObservable(AddPointEvent.class).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<AddPointEvent>() {
            @Override
            public void accept(AddPointEvent dataEvent) throws Exception {
                getDataFromServer();
            }
        });
    }

    @Override
    public BaseRecyclerAdapter<DevicePicInfo> getAdapter() {
        return new BaseRecyclerAdapter<DevicePicInfo>(this) {
            @Override
            public int getItemLayoutId(int viewType) {
                return R.layout.item_deviceunitinfo;
            }

            @Override
            public void bindData(RecyclerViewHolder holder, final int position) {
                super.bindData(holder, position);
                final DevicePicInfo info = getItemByPosition(position);
                boolean isCopy = info.isCopy();

                String label = "";

                if (isCopy) {
                    label = info.getUnitName() + "-复制";
                    holder.setText(R.id.picNameTv, info.getUnitName() + "-复制");
                } else {
                    label = info.getUnitName();
                }


                holder.setText(R.id.picNameTv, label);
                holder.setText(R.id.picNoTv, info.getDeviceName() + "-" + info.getLabel());
                long pointCount = info.getPointCount();
                if (pointCount == 0) {
                    pointCount = getPointCount(info.getPointList());
                }

                holder.setText(R.id.pointCountTv, "(" + pointCount + "个)");
                long createTime = info.getCreateTime();
                if (createTime != 0) {
                    holder.setText(R.id.timeTv, Kits.Date.getYmdhms(createTime));
                }

                holder.setChildOnClick(position, R.id.editIv, DeviceUnitListActivity.this);
                holder.setChildOnClick(position, R.id.showIv, DeviceUnitListActivity.this);
//                holder.setChildOnClick(position, R.id.copyIv, DeviceUnitListActivity.this);

                if (isCopyModel) {
                    holder.setVisibility(R.id.selectIv, View.VISIBLE);
                    if (selectList.contains(info)) {
                        holder.setImageResDrawable(R.id.selectIv, R.mipmap.select1);
                    } else {
                        holder.setImageResDrawable(R.id.selectIv, R.mipmap.select0);
                    }
                } else {
                    holder.setVisibility(R.id.selectIv, View.GONE);
                }

            }
        };
    }


    protected void showBottomDialog(final DevicePicInfo picInfo) {
        List<String> list = new ArrayList<>();
        list.add("修改");
        list.add("修改标签号");
        list.add("删除");
        list.add("插入");
        BottomListDialog bottomListDialog = new BottomListDialog(this, new BottomListDialog.BottomListSelectListener() {
            @Override
            public void itemClickCallback(String selectStr) {
                if (selectStr.equals("修改")) {
                    toAdd(1, picInfo.get_ID(), picInfo.getSortIndex());
                } else if (selectStr.equals("删除")) {
                    selectList.clear();
                    selectList.add(picInfo);
                    showSingleItemDelTip(picInfo);
//                    showDelTip();
                } else if (selectStr.equals("修改标签号")) {
                    showBroadPop(picInfo, "标签号", 4, InputDialog.broad1);
                } else {
                    toAdd(2, picInfo.get_ID(), picInfo.getSortIndex() + 1);
                }
            }
        });
        bottomListDialog.disPlay(list);
    }


    private void showSingleItemDelTip(final DevicePicInfo picInfo) {
        SubmitTipDialog submitTipDialog = new SubmitTipDialog(this, new SubmitTipDialog.SlectClickListener() {
            @Override
            public void submitClick() {
                EntityManager.getInstance().delDevicePicInfo(picInfo);
                List<DevicePicInfo> beforeList = EntityManager.getInstance().queryAllDeviceUnit_Le_sort(picInfo.getParentId(), picInfo.getUnitName(), picInfo.getSortIndex());
                List<DevicePicInfo> backList = EntityManager.getInstance().queryAllDeviceUnit_Gt_sort(picInfo.getParentId(), picInfo.getUnitName(), picInfo.getSortIndex());
                String startLable;
                if (beforeList.size() > 0) {
                    startLable = beforeList.get(beforeList.size()-1).getLabel();
                } else {
                    startLable = "001";
                }
                for (int i = 0; i < backList.size(); i++) {
                    backList.get(i).setLabel(getIndex(startLable, i + 1));
                }
                EntityManager.getInstance().saveDevicePicInfo(backList);

                getP().sendPointChagneEvent(deviceDbId, null);
                getDataFromServer();
            }

            @Override
            public void cancelClick() {

            }
        });
        submitTipDialog.display("温馨提示", "是否删除所选项" + "?", "取消", "删除");
    }


    private void showDelTip() {
        SubmitTipDialog submitTipDialog = new SubmitTipDialog(this, new SubmitTipDialog.SlectClickListener() {
            @Override
            public void submitClick() {
                Long[] picDbIds = new Long[selectList.size()];
                for (int i = 0; i < selectList.size(); i++) {
                    picDbIds[i] = selectList.get(i).get_ID();
                }
                getP().sendPointChagneEvent(deviceDbId, null);
                EntityManager.getInstance().delDevicePicInfo(selectList);
                repeatCountLabel();
                isCopyModel = false;
                bottonLayout.setVisibility(View.GONE);
                selectList.clear();
//                BusProvider.getBus().post(new AddPointEvent(deviceDbId,xxx));
                getDataFromServer();
            }

            @Override
            public void cancelClick() {

            }
        });
        submitTipDialog.display("温馨提示", "是否删除所选项" + "?", "取消", "删除");
    }

    @Override
    public void itemClick(int position) {
        DevicePicInfo info = mBaseAdapter.getItemByPosition(position);

        if (isCopyModel) {
            if (selectList.contains(info)) {
                selectList.remove(info);
            } else {
                selectList.add(info);
            }
            mBaseAdapter.notifyDataSetChanged();
        } else {
            if (info.getLableIsRepeat()) {
                showToast("请修改单元标签号");
            } else {
//                DelPointListActivity.lunch(this,1l);
                DevicePointsActivity.lunch(this, info.getPicPath(), info.get_ID());
            }
        }
    }


    public void toAdd(int operateType, Long picDbId, int sortIndex) {
        AddDeviceUnitActivity.lunch(this, deviceName, deviceDbId, operateType, picDbId, sortIndex);
    }

    @Override
    public void getDataFromServer() {
        String search = inputEt.getText().toString();
        List<DevicePicInfo> dataList = null;
        if (TextUtils.isEmpty(search)) {
            dataList = EntityManager.getInstance().queryAllDevicePic(deviceDbId);
        } else {
            dataList = EntityManager.getInstance().queryAllDevicePic(deviceDbId, search);
        }
//        Iterator<DevicePicInfo> iterator =  dataList.iterator();
//        while (iterator.hasNext()) {
//            DevicePicInfo picInfo = iterator.next();
//            if (AppContents.ISTEST && !picInfo.getLabel().equals("0072")) {
//                iterator.remove();
//            }
//        }

        for (DevicePicInfo picInfo : dataList) {
            NLog.d("getDataFromServer", picInfo.toString());
            if (picInfo.getPointCount() == 0) {
                int count = 0;
                for (DevicePointInfo devicePointInfo : picInfo.getPointList()) {
                    String childTypeEn = devicePointInfo.getChildTypeEn();
                    if ("KP".equals(childTypeEn)) {
                        count += devicePointInfo.getDeviceCount();
                    } else {
                        count++;
                    }
                }
                picInfo.setPointCount(count);
                EntityManager.getInstance().saveDevicePicInfo(picInfo);
            }
        }
        sort(dataList);
        onSuccess(true, dataList);
    }

    @Override
    public void getIntentData() {
        deviceName = getIntent().getStringExtra("devicename");
        deviceDbId = getIntent().getLongExtra("devicedbid", -1);
    }


    @Override
    public BasePresent newP() {
        return new BasePresent();
    }

    @Override
    public int getTitleLayoutResId() {
        return 0;
    }

    public static void lunch(Context context, String deviceName, Long deviceDbId) {
        Intent intent = new Intent(context, DeviceUnitListActivity.class);
        intent.putExtra("devicename", deviceName);
        intent.putExtra("devicedbid", deviceDbId);
        context.startActivity(intent);
    }

    @OnClick({R.id.rightIv, R.id.copyIv, R.id.copyBtn, R.id.delBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rightIv:
                List<DevicePicInfo> list = mBaseAdapter.getmList();
                Long picDbId = -1l;
                int sortIndex = 0;
                if (!Kits.Empty.check(list)) {
                    picDbId = list.get(list.size() - 1).get_ID();
                    sortIndex = list.get(list.size() - 1).getSortIndex();
                }
                toAdd(0, picDbId, sortIndex+1);
                break;
            case R.id.copyIv:
                if (!isCopyModel) {
                    isCopyModel = true;
                    mBaseAdapter.notifyDataSetChanged();
                    bottonLayout.setVisibility(View.VISIBLE);
                } else {
                    isCopyModel = false;
                    mBaseAdapter.notifyDataSetChanged();
                    bottonLayout.setVisibility(View.GONE);
                    selectList.clear();
                }

                break;
            case R.id.copyBtn:
                if (selectList.size() == 0) {
                    showToast("请选择复制项");
                } else {
                    showCopy(false);
                }
                break;
            case R.id.delBtn:
                if (selectList.size() == 0) {
                    showToast("请选择删除项");
                } else {
                    showDelTip();
                }
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        getDataFromServer();
    }

    @Override
    public boolean isNotWorkConnect() {
        return false;
    }

    @Override
    public void itemChildClick(int position, int viewId) {
        DevicePicInfo picInfo = mBaseAdapter.getItemByPosition(position);
        switch (viewId) {
            case R.id.editIv:
                showBottomDialog(mBaseAdapter.getItemByPosition(position));
//                toAdd(1, picInfo.get_ID());
                break;
            case R.id.delIv:
                showDelTip();
                break;
            case R.id.showIv:
                DevicePointsActivity.lunch(this, picInfo.getPicPath(), picInfo.get_ID());
                break;
            case R.id.copyIv:
                selectList.add(picInfo);
                showCopy(true);
                break;
        }
    }

    private void showCopy(final boolean isSingel) {
        String message;
        message = "是否复制所选" + selectList.size() + "项？如若修改参考物请在输入框填入新参考物！";
        CopyDialog submitTipDialog = new CopyDialog(this, new CopyDialog.SlectClickListener() {
            @Override
            public void submitClick(String releven, boolean autoSort) {
                for (DevicePicInfo picInfo : selectList) {
                    toCopy(picInfo, isSingel, autoSort, releven);
                }
                repeatCountLabel();
                isCopyModel = false;
                bottonLayout.setVisibility(View.GONE);
                selectList.clear();
                getDataFromServer();
            }

            @Override
            public void cancelClick() {

            }
        });
        submitTipDialog.display("温馨提示", message, "取消", "确定");
    }


    private Long toCopy(DevicePicInfo info, boolean isSingel, boolean autoSort, String reference) {
        String oldLabel = info.getLabel();
        long oldDbID = info.get_ID();
        String oldPicPath = info.getPicPath();
        boolean labelIsRepeat = info.getLableIsRepeat();
        boolean oldIsCopy = info.isCopy();
        String oldReference = info.getReference();
        String oldDeviceName = info.getDeviceName();

        File picFile = new File(oldPicPath);
        String fileName = picFile.getName();

        int index = fileName.lastIndexOf(".");
        String realName = fileName.substring(0, index);


        String str = UUID.randomUUID().toString();
        String newFileName = str.replace("-", "");
        String newFilePath = oldPicPath.replace(realName, newFileName);
        Kits.File.copyFile(oldPicPath, newFilePath);
        NLog.d(TAG, "原图片的_ID=" + info.get_ID());
        List<DevicePointInfo> pointList = EntityManager.getInstance().queryDevicePointInfoIByParentid(info.get_ID());
        NLog.d(TAG, "原图片的点数=" + pointList.size());
        if (!TextUtils.isEmpty(reference)) {
            info.setReference(reference);
            info.setDeviceName(reference);
        }

        info.set_ID(null);
        info.setPicPath(newFilePath);
        if (autoSort) {
            info.setLableIsRepeat(false);
        } else {
            info.setLableIsRepeat(true);
        }
        info.setCopy(true);
        Long dbId = EntityManager.getInstance().saveDevicePicInfo(info);
        List dbList = EntityManager.getInstance().queryDevicePointInfoIByParentid(dbId);
        EntityManager.getInstance().delDevicePointInfo(dbList);
        NLog.d(TAG, "新图片的_ID=" + dbId);
        for (DevicePointInfo pointInfo : pointList) {
            pointInfo.setParentId(dbId);
            pointInfo.set_ID(null);
        }
        EntityManager.getInstance().savePointInfo(pointList);
        info.set_ID(oldDbID);
        info.setLabel(oldLabel);
        info.setPicPath(oldPicPath);
        info.setLableIsRepeat(labelIsRepeat);
        info.setCopy(oldIsCopy);
        info.setReference(oldReference);
        info.setDeviceName(oldDeviceName);
        info.setCreateTime(Calendar.getInstance().getTimeInMillis());
        if (isSingel) {
            DevicePointsActivity.lunch(this, newFilePath, dbId);
        }
        getP().sendPointChagneEvent(deviceDbId, null);
        return dbId;
    }


    private String getIndex(String startLabel, long labelIndex) {
        String expendStr;
        int startIndex = Integer.parseInt(startLabel);
        labelIndex = labelIndex + startIndex;
        if (labelIndex < 10) {
            expendStr = "000" + labelIndex;
        } else if (labelIndex >= 10 && labelIndex < 100) {
            expendStr = "00" + labelIndex;
        } else if (labelIndex >= 100 && labelIndex < 1000) {
            expendStr = "0" + labelIndex;
        } else {
            expendStr = "" + labelIndex;
        }
        return expendStr;
    }

    private void sort(List<DevicePicInfo> dataList) {
        labelMap.clear();
//        Collections.sort(dataList, new Comparator<DevicePicInfo>() {
//            @Override
//            public int compare(DevicePicInfo o1, DevicePicInfo o2) {
//                String indexStr = o1.getUnitName()+o1.getDeviceName()+o1.getLabel();
//                String index2Str = o2.getUnitName()+o2.getDeviceName()+o2.getLabel();
//                int result = indexStr.compareTo(index2Str);
//                return result;
//            }
//        });
        for (DevicePicInfo picInfo : dataList) {
            List<String> labelList = labelMap.get(picInfo.getUnitName());
            if (null == labelList) {
                labelList = new ArrayList<>();
                labelMap.put(picInfo.getUnitName(), labelList);
            }
            labelList.add(picInfo.getLabel());
        }

        for (DevicePicInfo picInfo : dataList) {
            List<String> labelList = labelMap.get(picInfo.getUnitName());
            int firstIndex = labelList.indexOf(picInfo.getLabel());
            int lastIndex = labelList.lastIndexOf(picInfo.getLabel());
            if (picInfo.getLableIsRepeat() && firstIndex == lastIndex) {
                picInfo.setLableIsRepeat(false);
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (isCopyModel) {
            isCopyModel = false;
            mBaseAdapter.notifyDataSetChanged();
            bottonLayout.setVisibility(View.GONE);
            selectList.clear();
        } else {
            super.onBackPressed();
        }
    }

    private int getPointCount(List<DevicePointInfo> pointInfos) {
        int count = 0;
        for (DevicePointInfo pointInfo : pointInfos) {
            String childTypeEn = pointInfo.getChildTypeEn();
            if ("KP".equals(childTypeEn)) {
                count += pointInfo.getDeviceCount();
            } else {
                count++;
            }
        }
        return count;
    }


    public void repeatCountLabel() {
        List<String> unitNameList = new ArrayList<>();
        for (DevicePicInfo picInfo : selectList) {
            if (unitNameList.contains(picInfo.getUnitName())) {
                break;
            }
            unitNameList.add(picInfo.getUnitName());
            List<DevicePicInfo> list = EntityManager.getInstance().queryAllDeviceUnitByName(picInfo.getParentId(), picInfo.getUnitName());
            String startLable = "0000";
//            if (list.size() > 0) {
//                startLable = list.get(0).getLabel();
//            }
            for (int i = 0; i < list.size(); i++) {
                DevicePicInfo info = list.get(i);
                info.setLabel(getIndex(startLable, i + 1));
            }
            EntityManager.getInstance().saveDevicePicInfo(list);
        }
    }

    public void repeatCountLabel(DevicePicInfo picInfo, String newLable) {
        List<DevicePicInfo> list = EntityManager.getInstance().queryAllDeviceUnitByName(picInfo.getParentId(), picInfo.getUnitName());


        int targetLable = Integer.parseInt(picInfo.getLabel());
        Iterator<DevicePicInfo> iterator = list.iterator();
        while (iterator.hasNext()) {
            DevicePicInfo devicePicInfo = iterator.next();
            int label = Integer.parseInt(devicePicInfo.getLabel());
            if (label < targetLable) {
                iterator.remove();
            }
        }
        String startLable = newLable;


        for (int i = 0; i < list.size(); i++) {
            DevicePicInfo info = list.get(i);
            info.setLabel(getIndex(startLable, i));
        }
        EntityManager.getInstance().saveDevicePicInfo(list);
        getDataFromServer();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void showBroadPop(final DevicePicInfo picInfo, String label, int maxCount, String[] paramers) {
        InputDialog inputDialog = new InputDialog(this, label, new InputDialog.InputCompleteListener() {
            @Override
            public void onInputComplete(String value) {
                repeatCountLabel(picInfo, value);
            }
        }, maxCount);
        inputDialog.disPlay(paramers);
    }
}
